<script setup>
import { reactive, ref } from 'vue'
import Api from '@/api/api.js'
import { setToken } from '@/utils/auth.js'
import { useRouter } from 'vue-router'
const router = useRouter()
const ruleFormRef = ref()
const ruleForm = reactive({
    account: '',
    password: ''
})

const rules = reactive({
    account: [
        { required: true, message: 'Please input account name', trigger: 'blur' },
        { min: 3, max: 18, message: 'Length should be 3 to 18', trigger: 'blur' },
    ],
    password: [
        { required: true, message: 'Please input Password', trigger: 'blur' },
        { min: 3, max: 18, message: 'Length should be 3 to 18', trigger: 'blur' },
    ],
})
const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate(async (valid, fields) => {
        if (valid) {
            let { isSuccess, data: { uid, token, userName }, msg } = await Api.login(ruleForm)
            console.log('submit!', data)
            if (isSuccess) {
                // 存token到session，后续请求携带token
                setToken(token)
                router.push('/home')
            } else {
                alert(msg)
            }
        } else {
            console.log('validate error!', fields)
        }
    })
}

</script>
<template>
    <div class="login">
        <p class="login-title">
            后台管理系统
        </p>
        <div class="login-content">
            <div class="login-main">
                <div class="login-container">
                    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
                        status-icon>
                        <el-form-item label="用户名" prop="account">
                            <el-input v-model="ruleForm.account" />
                        </el-form-item>
                        <el-form-item label="密码" prop="password">
                            <el-input type="password" v-model="ruleForm.password" />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="success" @click="submitForm(ruleFormRef)">
                                登录
                            </el-button>
                        </el-form-item>
                    </el-form>

                </div>
            </div>
        </div>
    </div>
</template>
<style scoped></style>